
package com.fitns.user.service.baseConfig;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.fitns.user.conf.Constants;
import com.fitns.user.conf.ExcelConstants;
import com.fitns.user.dao.baseConfig.TbPersonLederDao;
import com.fitns.user.dto.baseConfig.TbPersonLederDTO;
import com.fitns.user.dto.baseConfig.TbPersonLederVO;
import com.fitns.user.model.baseConfig.TbPersonLedger;
/*import com.fitns.user.dao.TbPersonLederDao;
import com.fitns.user.dto.TbPersonLederDTO;
import com.fitns.user.model.TbPersonLedger;*/
import com.fitns.user.utils.DateUtil;
import com.fitns.user.utils.DeEnCode;
//import com.fitns.user.vo.TbPersonLederVO;
import com.github.pagehelper.PageInfo;
import com.xiaoleilu.hutool.lang.Validator;

@Service
public class TbPersonLederService {

	@Autowired
	private TbPersonLederDao tbPersonLederDao;
	
	/** 新增人员台账 */
	@Transactional
	public int insertPersonLeder(TbPersonLederDTO tbPersonLederDTO,String phone) {
		TbPersonLedger record =  new TbPersonLedger();
		BeanUtils.copyProperties(tbPersonLederDTO, record);
		record.setId(tbPersonLederDTO.getId());
		record.setGuardTime(new Date());
		record.setName(DeEnCode.encode(tbPersonLederDTO.getName()));
		//对用户手机号进行加密
		record.setPhone(DeEnCode.encode(tbPersonLederDTO.getPhone()));
		//对用户身份证进行加密
		record.setIdCard(DeEnCode.encode(tbPersonLederDTO.getIdCard()));
		return tbPersonLederDao.insertSelective(record);
	}
	
	
	public int deletePersonById(long id) {
        return tbPersonLederDao.deletePersonById(id);
	}
	
	/** 修改人员台账 */
	@Transactional
	public int updatePersonLeder(TbPersonLederDTO tbPersonLederDTO) {
		TbPersonLedger record =  new TbPersonLedger();
		BeanUtils.copyProperties(tbPersonLederDTO, record);
		record.setId(tbPersonLederDTO.getId());
		record.setGuardTime(new Date());
		//record.setLeaveTime(new Date());
		//对用户名称进行加密
		
		return tbPersonLederDao.updateByPrimaryKeySelective(record);
	}
	
	/** 查看人员台账 */
	public PageInfo<TbPersonLederVO> selectBannerList(TbPersonLederDTO tbPersonLederDTO) {
		tbPersonLederDTO.pageHandle();
		//base64解密
		//先查询出来数据，在去解密
		List<TbPersonLederVO>  selectPersionList =tbPersonLederDao.selectPersonLeder(tbPersonLederDTO);
		//声明全局
		PageInfo<TbPersonLederVO> pageInfo;
		/*PageInfo pageInfo2 = null;
		PageInfo<TbPersonLederVO> pageInfo3 = null;*/
		 List<TbPersonLederVO> userVOS=new ArrayList<>(); 
		 //当参数不为null时
	        if(Validator.isNotNull(selectPersionList)) {
	        	selectPersionList.forEach(userVO -> {
	        		//调用下面的deCodeUser方法
	        		TbPersonLederVO vo=this.deCodeUser(userVO);
	                userVOS.add(vo);
	            });
	            pageInfo = new PageInfo<>(userVOS);
	        }else {
	            pageInfo = new PageInfo<>(selectPersionList);
	        }
	        return pageInfo;
	    }
	  //解密 用户姓名   手机号  身份证号
    public TbPersonLederVO deCodeUser(TbPersonLederVO tbPersonLederVO){
    	TbPersonLederVO vo = new TbPersonLederVO();
        BeanUtils.copyProperties(tbPersonLederVO,vo);
        vo.setName(DeEnCode.decode(tbPersonLederVO.getName()));
        vo.setPhone(DeEnCode.decode(tbPersonLederVO.getPhone()));
        vo.setIdCard(DeEnCode.decode(tbPersonLederVO.getIdCard()));
        return vo;
    }
	
	/* //解密 用户姓名   手机号  身份证号
    public TbPersonLederVO deCodeUserPerson(TbPersonLedger userVO){
    	TbPersonLederVO vo = new TbPersonLederVO();
        BeanUtils.copyProperties(userVO,vo);
        vo.setName(DeEnCode.decode(userVO.getName()));
        vo.setPhone(DeEnCode.decode(userVO.getPhone()));
        vo.setIdCard(DeEnCode.decode(userVO.getIdCard()));
        return vo;
    }*/
    //解密 用户姓名   手机号  身份证号
    public TbPersonLederVO deCodeUserPerson(TbPersonLedger userVO){
    	TbPersonLederVO vo = new TbPersonLederVO();
        //BeanUtils.copyProperties(String.valueOf(userVO).toString(),vo);
    	String uv = vo.toString();
        BeanUtils.copyProperties(userVO,uv);
        //BeanUtils.copyProperties(userVO,vo);
        vo.setName(DeEnCode.decode(userVO.getName()));
        vo.setPhone(DeEnCode.decode(userVO.getPhone()));
        vo.setIdCard(DeEnCode.decode(userVO.getIdCard()));
        return vo;
    }
  
	public TbPersonLedger selectPersonLederById(long id) {
		return tbPersonLederDao.selectPersonLederById(id);
	}
	
	
	@Transactional
	public Integer inserIcon(TbPersonLederDTO tbPersonLederDTO) {
		TbPersonLedger record  = new TbPersonLedger();
		BeanUtils.copyProperties(tbPersonLederDTO, record);
		if(Validator.isNull(tbPersonLederDTO.getId())){
			
			return this.insertPersonLeder(tbPersonLederDTO, null);
		}else {
			record.setImage(tbPersonLederDTO.getImage());
			record.setModifyTime(new Date());
			return tbPersonLederDao.updateByPrimaryKey(record);
		}

	}
	

	/** 
	 *  
	 * ################### exclue文件导入，批量导入在service中做了处理，所以sql中新增的sql没有用到foeach循环 #####################
	 * 
	 * */
	
    @Transactional
    public List<TbPersonLederVO> importExcel(List<List<String>> excelList){
        List<TbPersonLederVO> dtoList=new ArrayList<>();
        List<TbPersonLederVO> msgList=new ArrayList<>();

        for (int i = 1; i <excelList.size() ; i++) {
            String number=excelList.get(i).get(0);
            if(!StringUtils.isEmpty(number)){
            	TbPersonLederVO facilityDataVo=this.validateExcel(excelList.get(i),i);
                if(!StringUtils.isEmpty(facilityDataVo.getMsg())){
                    msgList.add(facilityDataVo);
                }else {
                	TbPersonLederVO dataVo=this.importDetail(excelList.get(i));
                    dtoList.add(dataVo);
                }
            }
        }
        if(Validator.isEmpty(msgList)||msgList.size()==0){
            if(Validator.isNotEmpty(dtoList)&&dtoList.size()!=0){
                dtoList.forEach(facilityDataVo -> {
                	TbPersonLedger facilityData=new TbPersonLedger();
                    BeanUtils.copyProperties(facilityDataVo,facilityData);
                 /*   //对用户手机号进行加密
                    facilityData.setPhone(DeEnCode.encode(facilityDataVo.getPhone()));
                    facilityData.setName(DeEnCode.encode(facilityDataVo.getName()));
                    facilityData.setIdCard(DeEnCode.decode(facilityDataVo.getIdCard()));*/
                    tbPersonLederDao.inserts(facilityData);
                });
            }else {
            	TbPersonLederVO facilityDataVo=new TbPersonLederVO();
                facilityDataVo.setMsg(ExcelConstants.PERSON_LEDGER_IMPORT.EXCEL_IS_NULL);
                msgList.add(facilityDataVo);
            }
        }

        return msgList;

    }
	
    /** excel文件导入字段必填字段 */
    public TbPersonLederVO validateExcel(List<String> excelList, int i){
    	TbPersonLederVO facilityDataVo=new TbPersonLederVO();
        StringBuilder msg = new StringBuilder();
       
        if(StringUtils.isEmpty(excelList.get(0))){
            msg.append("第"+(i+1)+"行"+ExcelConstants.PERSON_LEDGER_IMPORT.PERSON_LEDGER_NAME_IS_NULL);
        }
        if(StringUtils.isEmpty(excelList.get(1))){
            msg.append("第"+(i+1)+"行"+ExcelConstants.PERSON_LEDGER_IMPORT.PERSON_LEDGER_ID_CARD_IS_NULL);
        }
        if(StringUtils.isEmpty(excelList.get(3))){
            msg.append("第"+(i+1)+"行"+ExcelConstants.PERSON_LEDGER_IMPORT.PERSON_LEDGER_ATTENDANCE_WAY);
        }
        if(StringUtils.isEmpty(excelList.get(9))){
            msg.append("第"+(i+1)+"行"+ExcelConstants.PERSON_LEDGER_IMPORT.PERSON_LEDGER_PHONE);
        }
        if(StringUtils.isEmpty(excelList.get(12))){
            msg.append("第"+(i+1)+"行"+ExcelConstants.PERSON_LEDGER_IMPORT.PERSON_LEDGER_SEX_IS_NULL);
        }
        if(StringUtils.isEmpty(excelList.get(15))){
            msg.append("第"+(i+1)+"行"+ExcelConstants.PERSON_LEDGER_IMPORT.PERSON_LEDGER_TERMINAL);
        }
        if(!StringUtils.isEmpty(msg)){
            facilityDataVo.setMsg(msg.toString());
        }
        return facilityDataVo;
    }

    public TbPersonLederVO importDetail(List<String> excelList){
    	TbPersonLederVO facilityDataVo=new TbPersonLederVO();
    	/*//不为string类型的if转换一下类型，免得导入文件时候乱码报错
    	//Validator来自于第三方   第三方pom<dependency>
		<groupId>com.xiaoleilu</groupId>
		<artifactId>hutool-all</artifactId>
		<version>3.2.1</version>
	</dependency>*/
    	//Integer类型跟flout类型要做非空判断不然报错下面两句代码为示例
    	/* if(Validator.isNotNull(excelList.get(22))&&!"".equals(excelList.get(22))) {
             facilityDataVo.setApprovedNum(Integer.valueOf(excelList.get(22)));
    	 }*/
    	 facilityDataVo.setName(excelList.get(0));
    	 facilityDataVo.setSex(excelList.get(1));
         facilityDataVo.setIdCard(excelList.get(2));
         facilityDataVo.setPhone(excelList.get(3));
         facilityDataVo.setAddress(excelList.get(4));
         facilityDataVo.setAttendanceWay(excelList.get(5));
         facilityDataVo.setTerminal(excelList.get(6));
         facilityDataVo.setSos(excelList.get(7));
         facilityDataVo.setOneButton(excelList.get(8));
         facilityDataVo.setTwoButton(excelList.get(9));
         facilityDataVo.setThreeButton(excelList.get(10));
         if(Validator.isNotNull(excelList.get(11))) {
        	 facilityDataVo.setIsEnter(Boolean.valueOf(excelList.get(11)));
         }
         facilityDataVo.setSocialNum(excelList.get(12));
         facilityDataVo.setRecordNum(excelList.get(13));
         facilityDataVo.setContractNum(excelList.get(14));
    	 if(Validator.isNotNull(excelList.get(15))) {
             facilityDataVo.setGuardTime(DateUtil.parseStrToDate(excelList.get(15), Constants.DATESTR));
         }
    	 if(Validator.isNotNull(excelList.get(16))) {
    		 facilityDataVo.setLeaveTime(DateUtil.parseStrToDate(excelList.get(16), Constants.DATESTR));
    	 }
    	 facilityDataVo.setRemark(excelList.get(17));
    	 facilityDataVo.setType(excelList.get(18));
    	 facilityDataVo.setImage(excelList.get(19));
        //facilityDataVo.setIsEnter(excelList.get(7));
        return facilityDataVo;
    }
    /** 
	 *  
	 * ################### exclue文件导入service层到此为止
	 * 
	
	 * */
    
 
    ////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////
    
    
    
    /** 
   	 *  
   	 * ################### exclue文件导出，也就是从数据库导出文件到exclue
   	 * 
   	 * */
    public List<List<String>> export(TbPersonLederDTO tbPersonLederDTO){
        List<TbPersonLedger> facilityDataList=tbPersonLederDao.searchForExport(tbPersonLederDTO);
      //List<List<String>> list;
		
        List<List<String>> excelList = new ArrayList<>();
        for (int i = 0; i < facilityDataList.size(); i++) {
            if(i==0){
                excelList.add(this.getRowHeader(ExcelConstants.PERSON_LEDGER_IMPORT_HEADER.class));
            }
            excelList.add(this.getrow(facilityDataList.get(i),i));
        }
     /* List<String> userVOS=new ArrayList<>(); 
        if(Validator.isNotNull(facilityDataList)) {
        	facilityDataList.forEach(userVO -> {
        		TbPersonLederVO vo=this.deCodeUserPerson(userVO);
                userVOS.add(vo);
            });
        	//List excelList = new ArrayList<>();
        	excelList.add(userVOS);
        }else {
        	//List excelList = new ArrayList<>();
        	excelList.add(facilityDataList);
        }*/
        //List<List<String>> list2;
		//return list2;
        return excelList;
    }

    public List<String> getRowHeader(Class clazz){
        Field[] fields=clazz.getDeclaredFields();
        List<String> rowHeader = new ArrayList<>();
        for(int i=0;i<fields.length-1;i++){
            try {
                Object object =fields[i].get(clazz);
                String value = object.toString();
                rowHeader.add(value);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return rowHeader;
    }

    public List<String> getrow(TbPersonLedger tbPersonLedger, int i){
        List<String> row = new ArrayList<>();
       
        //row.add(String.valueOf(i + 1));
        row.add(tbPersonLedger.getName());
        row.add(tbPersonLedger.getSex());
        row.add(tbPersonLedger.getIdCard());
        row.add(tbPersonLedger.getPhone());
        row.add(tbPersonLedger.getAddress());
        row.add(tbPersonLedger.getAttendanceWay());
        row.add(tbPersonLedger.getTerminal());
        row.add(tbPersonLedger.getSos());
        row.add(tbPersonLedger.getOneButton());
        row.add(tbPersonLedger.getTwoButton());
        row.add(tbPersonLedger.getThreeButton());
        if(Validator.isNull(tbPersonLedger.getIsEnter())) {
            row.add("");
        }else {
            row.add(String.valueOf(tbPersonLedger.getIsEnter()));
        }
        row.add(tbPersonLedger.getSocialNum());
        row.add(tbPersonLedger.getRecordNum());
        row.add(tbPersonLedger.getContractNum());
        //if else处理的是数据库要导出的数据中不为string的字段，
        //时间格式的就是这样的写法，因为工具类中已经对时间处理了，固定 的写法
        
        if(Validator.isNull(tbPersonLedger.getGuardTime())) {
            row.add("");
        }else {
            row.add(DateUtil.parseDateToStr(tbPersonLedger.getGuardTime(),Constants.DATESTR));
        }
        if(Validator.isNull(tbPersonLedger.getLeaveTime())) {
            row.add("");
        }else {
            row.add(DateUtil.parseDateToStr(tbPersonLedger.getGuardTime(),Constants.DATESTR));
        }
        row.add(tbPersonLedger.getRemark());
        row.add(tbPersonLedger.getType());
        row.add(tbPersonLedger.getImage());
        //row.add(tbPersonLedger.getSex());
       return row;
    }
}


